const { error } = require("console");
const fs = require("fs");
const path = require("path");
const url = require("url");
const ejs = require("ejs");

// 私有方法
const getFileMineSync = function (extname) {
  let data = fs.readFileSync("./data/mime.json"); // 同步方法
  let mineObj = JSON.parse(data.toString());
  return mineObj[extname]
}

let app = {
  static: (req, res, staticPath) => {
    // 1. 获取地址
    let pathname = url.parse(req.url).pathname;
    let extname = path.extname(pathname); // 获取后缀名

    if (pathname !== "/favicon.ico") {
      try {
        // 通过 fs 模块读取文件
        let data = fs.readFileSync('./' + staticPath + pathname);
        if (data) {
          const responseHeader = getFileMineSync(extname);
          res.writeHead(200, { 'Content-Type': `${responseHeader};charset='utf-8'` });
          res.end(data);
        }
      } catch (error) {}
    }
  },
  login: (req, res) => {
    // 处理登陆业务的逻辑
    ejs.renderFile("./views/form.ejs", {}, (err, data) => {
      res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
      res.end(data);
    })
  },
  news: (req, res) => {
    // 处理news业务的逻辑
    res.end("news");
  },
  doLogin: (req, res) => {
    // 处理news业务的逻辑
    // 获取 post 传值
    let postData = "";
    req.on("data", (chunk) => {
      postData += chunk;
    })
    req.on("end", () => {
      console.log(postData);
      res.end(postData);
    })
  },
  error: (req, res) => {
    // 处理news业务的逻辑
    res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' });
    res.end("404这个页面不存在");
  },
}

// app.login('req','res')
// app['login']('req','res')

module.exports = app;
